<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="judgeAdd"
          :disabled="buttonShow"
        >新增
        </el-button>
<!--        v-hasPermi="['system:anjuan:add']"-->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="single"
          icon="el-icon-bottom"
          size="mini"
          @click="judgeInsert"
        >插入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"

        >修改
        </el-button>
<!--        v-hasPermi="['system:anjuan:edit']"-->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleDelete"

        >删除
        </el-button>
<!--        v-hasPermi="['system:anjuan:remove']"-->
      </el-col>
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="singleTable"  :row-style="{height: '10px'}" highlight-current-row height="650" v-loading="loading" :data="anjuanList"
               @current-change="handleCurrentChange" style="margin-top: 20px">
      <el-table-column label="总卷号" align="center" prop="zongJuanNo" width="80"/>
      <el-table-column label="档号" align="center" prop="dangNo" width="130"/>
      <el-table-column label="案卷题名" align="center" prop="anJuanName" />
      <el-table-column label="卷标" align="center" prop="juanNo" width="60"/>
      <el-table-column label="创建时间" align="center" prop="creationTime" width="100"/>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改查看案卷信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1700px" append-to-body>
      <el-form  @submit.native.prevent ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-form-item label="案卷题名" prop="anJuanName">
            <el-input v-model="form.anJuanName" placeholder="请输入案卷题名"/>
          </el-form-item>
          <el-col :span="12">
            <el-form-item label="编制单位" prop="xingChengDanWei">
              <el-input v-model="form.xingChengDanWei" placeholder="请输入形成单位"/>
            </el-form-item>
            <el-form-item label="兰图张数" prop="lanTuZhangShu">
              <el-input v-model="form.lanTuZhangShu" placeholder="请输入兰图张数"/>
            </el-form-item>
            <!--            第三列-->
            <el-form-item label="底图张数" prop="diTuZhangShu">
              <el-input v-model="form.diTuZhangShu" placeholder="请输入底图张数"/>
            </el-form-item>
            <el-form-item label="文字材料张数" prop="wenZiCaiLiaoZhangShu">
              <el-input v-model="form.wenZiCaiLiaoZhangShu" placeholder="请输入文字材料张数"/>
            </el-form-item>
            <el-form-item label="档号" prop="dangNo">
              <el-input v-model="form.dangNo" placeholder="请输入档号"/>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <!--            第四列-->
            <el-form-item label="库号" prop="kuNum">
              <el-input v-model="form.kuNum" placeholder="请输入库号"/>
            </el-form-item>
            <el-form-item label="列号" prop="leiNum">
              <el-input v-model="form.leiNum" placeholder="请输入列号"/>
            </el-form-item>
            <el-form-item label="架号" prop="jiaNum">
              <el-input v-model="form.jiaNum" placeholder="请输入架号"/>
            </el-form-item>
            <el-form-item label="层数" prop="cengShu">
              <el-input v-model="form.cengShu" placeholder="请输入层数"/>
            </el-form-item>
            <el-form-item label="总卷号" prop="zongJuanNo">
              <el-input v-model="form.zongJuanNo" placeholder="总卷号"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addAnjuan,
    delAnjuan,
    getAnjuan,
    listAnjuan,
    updateAnjuan,
    selectLastZongJuanNo,
    getMaxFeileiNo
  } from "@/api/system/shiti_anjuan";
  import moment from "moment";
  import { v4 as uuidv4 } from 'uuid';

  export default {
    name: "Anjuan",
    dicts: ['security_dict'],
    props: {
      parentData: Object,
      mergeTime: Number,
      ifDel:Number
    },
    data() {
      return {
        buttonShow:true,
        ifInsert:0,
        showAdvanceSearch: false,//初始时为简单搜索模式
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        allId: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 查看案卷信息表格数据
        anjuanList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          gid: null,
          gongChengName: null,
          anJuanName: null,
          dangNo: null,
          fenLeiNo: null,
          anJuanNo: null,
          zongJuanNo: null,
          juanNo: null,
          secretLevel: null,
          secretLevelName: null,
          storageLife: null,
          storageLifeName: null,
          lanTuZhangShu: null,
          diTuZhangShu: null,
          wenZiCaiLiaoZhangShu: null,
          bianZhiDate: null,
          xingChengDanWei: null,
          creationTime: null,
          kuNum: null,
          leiNum: null,
          jiaNum: null,
          cengShu: null,
          wenJianShu: null,
          AnJuanStatus: null,
          yuLiuA: null,
          yuLiuB: null,
          yuLiuC: null,
          yuLiuD: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          anJuanName: [
            {required: true, message: "案卷题名不能为空", trigger: "blur"}
          ],
          xingChengDanWei: [
            {required: true, message: "形成单位不能为空", trigger: "change"}
          ]
        }
      };
    },
    created() {

    },
    watch: {
      parentData: {
        deep: true,
        handler(newVal, oldVal) {
          if (newVal) {
            this.buttonShow=false;
            this.getList();
          } else {
            this.buttonShow=true;
            this.anjuanList = null;
            this.total = 0;
            this.loading = false;

          }
        }
      },
      mergeTime() {
        this.editAll();
      },
      ifDel() {
        this.DeleteAll();
      }
    },
    methods: {
      //更新卷标，总卷号,档号
      async setSerialNumber(number) {
          let query = {gid: this.parentData.id};
          listAnjuan(query).then(res => {
            let allId = res.rows.map(row => row.id);
            let zjn = this.currentRow.zongJuanNo+number;
            let ajn = this.currentRow.anJuanNo+number;
            for (let i = this.currentRow.juanNo-1; i < allId.length; i++) {
              console.log(i)
              let dn = this.parentData.xingChengNianDu + '-' + this.currentRow.fenLeiNo + '-' + this.currentRow.storageLife + '-' + ajn;
              const myQuery = {id: allId[i], juanNo: i + 1+number, zongJuanNo: zjn, dangNo: dn,anJuanNo:ajn};
              zjn += 1;
              ajn += 1;
              updateAnjuan(myQuery);
            }
            if(number!==1){
              this.$modal.msgSuccess("删除成功");
              this.getList()
            }
            this.getList()
          });
      },
      //生成时间
      editAll() {
        let time = moment().format('YYYY-MM-DD');
        let query = {gid: this.parentData.id};
        listAnjuan(query).then(res => {
          let allId = res.rows.map(row => row.id);
          for (let i = 0; i < allId.length; i++) {
            const myQuery = {id: allId[i], yuLiuA: time};
            updateAnjuan(myQuery);
          }
        });
      },
      async DeleteAll() {
          let query = { gid: this.parentData.id };
          let res = await listAnjuan(query);
          let allId = res.rows.map(row => row.id);
          console.log(allId.length)
          if (allId.length!==0){
            await delAnjuan(allId);
          }
      },
      //列表选中项发生改变时触发
      handleCurrentChange(val) {
        this.currentRow = val;
        // this.ids = val.map(item => item.id)
        // this.single = val.length!==1
        // this.multiple = !val.length
        this.single = val === null;
        this.ids = [];
        if (val != null) {
          this.ids.push(val.id);
          this.showAnjuan(val.id);
          // this.showData();
          // this.ifShow=true;
        }
      },
      /** 查询查看案卷信息列表 */
      getList() {
        this.loading = true;
        this.queryParams.gid = this.parentData.id;
        this.queryParams.gongChengName = this.parentData.engName;
        listAnjuan(this.queryParams).then(response => {
          response.rows.map(row=>{row.dangNo=row.dangNo.substring(0, 11)+'0'+row.anJuanNo.toString()})
          this.anjuanList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          gid: null,
          gongChengName: null,
          anJuanName: null,
          dangNo: null,
          fenLeiNo: null,
          anJuanNo: null,
          zongJuanNo: null,
          juanNo: null,
          secretLevel: null,
          secretLevelName: null,
          storageLife: null,
          storageLifeName: null,
          lanTuZhangShu: null,
          diTuZhangShu: null,
          wenZiCaiLiaoZhangShu: null,
          bianZhiDate: null,
          xingChengDanWei: null,
          creationTime: null,
          kuNum: null,
          leiNum: null,
          jiaNum: null,
          cengShu: null,
          wenJianShu: null,
          AnJuanStatus: null,
          yuLiuA: null,
          yuLiuB: null,
          yuLiuC: null,
          yuLiuD: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      judgeAdd(){
        if (this.total===this.parentData.anJuanShu){
          this.$modal.msgError('该工程案卷数已到达上限')
        }else {
          this.handleAdd()
        }
      },
      judgeInsert(){
        if (this.total===this.parentData.anJuanShu){
          this.$modal.msgError('该工程案卷数已到达上限')
        }else {
          this.handleInsert()
        }
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      async handleAdd() {
        this.reset();
        this.ifInsert=0;
        this.form.anJuanName = this.parentData.engName + '-';
        this.form.secretLevel = this.parentData.engAddress;
        this.form.storageLife = this.parentData.storageLife;
        this.form.fenLeiNo = this.parentData.daLeiNo + this.parentData.shuLeiNo + this.parentData.xiaoLeiNo;
        const zongJuanNo = await selectLastZongJuanNo();
        this.form.zongJuanNo = zongJuanNo + 1;
        let query = {pageNum: 1, pageSize: 1, fenLeiNo: this.form.fenLeiNo};
        const maxFeileiNoResponse = await getMaxFeileiNo(query);
        if (maxFeileiNoResponse.rows.length === 0) {
          this.form.anJuanNo = 1;
        } else {
          this.form.anJuanNo = maxFeileiNoResponse.rows[0]['anJuanNo'] + 1;
        }
        this.form.dangNo = this.parentData.xingChengNianDu + '-' + this.form.fenLeiNo + '-' + this.form.storageLife + '-0' + this.form.anJuanNo;
        this.open = true;
        this.title = "添加案卷信息";
      },
      async handleInsert() {
        this.reset();
        this.form.anJuanName = this.parentData.engName + '-';
        this.form.fenLeiNo = this.currentRow.fenLeiNo;
        this.form.zongJuanNo = this.currentRow.zongJuanNo;
        this.form.anJuanNo=this.currentRow.anJuanNo;
        this.form.dangNo = this.parentData.xingChengNianDu + '-' + this.currentRow.fenLeiNo + '-' + this.currentRow.storageLife + '-0' + this.currentRow.anJuanNo;
        this.form.juanNo=this.currentRow.juanNo;
        this.open = true;
        this.title = "插入案卷";
      },
      showAnjuan(anjuanId) {
        const id = anjuanId
        getAnjuan(id).then(response => {
          this.form = response.data;
          this.$emit('transport', this.form); // 触发名为 'child-event' 的自定义事件并传递数据
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        const id = row.id || this.ids
        getAnjuan(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改案卷信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateAnjuan(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.getData();
            }
          }
        });
      },
      async getData() {
        this.form.id = uuidv4();
        this.form.gid = this.parentData.id;
        this.form.gongChengName = this.parentData.engName;
        this.form.projectStatus = 0;
        this.form.creationTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.form.secretLevel = this.parentData.engAddress;
        this.form.storageLife = this.parentData.storageLife;
        this.form.bianZhiDate = this.parentData.bianZhiDateEnd;
        // this.form.fenLeiNo = this.parentData.daLeiNo + this.parentData.shuLeiNo + this.parentData.xiaoLeiNo;
        this.form.yuLiuC = this.parentData.xingChengNianDu;
        // Use await to wait for the promises to resolve
        // const zongJuanNo = await selectLastZongJuanNo();
        // this.form.zongJuanNo = zongJuanNo + 1;
        // let query = { pageNum: 1, pageSize: 1, fenLeiNo: this.form.fenLeiNo };
        // const maxFeileiNoResponse = await getMaxFeileiNo(query);
        // this.form.anJuanNo = maxFeileiNoResponse.rows[0]['anJuanNo'] + 1;
        // this.form.dangNo = this.parentData.xingChengNianDu + '-' + this.form.fenLeiNo + '-' + this.form.storageLife + '-' + this.form.anJuanNo;
        this.form.yuLiuB = 0;
        this.form.storageLifeName = this.tranValue(this.parentData.storageLife);
        this.form.secretLevelName = this.tranValue(this.parentData.secretLevel);
        this.form.dangNo=this.form.dangNo.substring(0, 11)+this.form.anJuanNo.toString()
        if (this.title==='插入案卷'){
            await this.setSerialNumber(1)
             addAnjuan(this.form).then(response => {
                this.$modal.msgSuccess("插入案卷成功");
                this.open = false;
                this.getList();
                this.$emit('addAnjuan', this.total + 1);
              })
        }else {
          this.form.juanNo = this.total + 1;
          addAnjuan(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
            this.$emit('addAnjuan', this.total + 1);
          });
        }
        // if (this.title==='新增案卷信息'){
        //   this.form.juanNo = this.total + 1;
        // }
        // Finally, call addAnjuan after all previous operations
      },
      /** 删除按钮操作 */
      async handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除该案卷吗？').then(function () {
          return delAnjuan(ids);
        }).then(() => {
          this.setSerialNumber(0);
          this.$emit('addAnjuan', this.total - 1);
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/anjuan/export', {
          ...this.queryParams
        }, `anjuan_${new Date().getTime()}.xlsx`)
      },
      tranValue(name) {
        if (name === 'NB') {
          return '内部'
        } else if (name === 'MM') {
          return '秘密'
        } else if (name === 'UM') {
          return '绝密'
        } else if (name === 'JM') {
          return '机密'
        } else if (name === 'GK') {
          return '公开'
        } else if (name === 'GN') {
          return '国内'
        } else if (name === 'C') {
          return '长期'
        } else if (name === 'D') {
          return '短期'
        } else if (name === 'Y') {
          return '永久'
        }
      }
    }
  };
</script>

<style>
  .el-form-item label {
    white-space: nowrap;
  }
</style>
